<?php
require_once( '../system/smarty.inc' );
require_once( '../system/tdao/Class_T_PATTERN.php' );
require_once( '../system/mdao/Class_M_OTHER.php' );
require_once( '../system/Class_ERROR.php' );
require_once( '../system/login.inc.php' );
require_once( '../system/aoki_m.php' );
require_once( '../system/Class_PWD.php' );

Class_PWD::valid_auth(AOKI_AUTH_T_PATTERN,$login['staff_auth']);


$forms = $_GET;

//if   ($login['staff_auth'] == 'G-2' || $login['staff_auth'] == 'G-3')  {
	//echo "権限はありません";
	//exit;
//}
	$dosearch = FALSE ;
	$dao = new Class_T_PATTERN;
	$matrix_cd = $_GET['matrix_cd'] ;
	if ($matrix_cd) {
		$dao->setTableNameWeek($matrix_cd);
	}
	//-----------権限 開始---------------------------------
	$area_zone_flg  = 0;
	$login_auth = $login['staff_auth'];
	if ($login_auth == 'G-2' ) {
		$area_cd   = $login['autoid'];
		$forms["sort"] = '2';
		$area_zone_flg = 2;
		$areauser = array($area_cd => $login['staff_id']." ".$login['staff_name'] );
		$forms['area_cd'] =  $area_cd;
	}else if ($login_auth == 'G-3' ) {
		$zone_cd   = $login['autoid'];
		$forms["sort"] = '3';
		$area_zone_flg = 3;
		$zoneuser = array($zone_cd => $login['staff_id']." ".$login['staff_name'] );
		$forms['zone_cd'] = $zone_cd;
	}else {
		// PLEASE_SELECT_ARR ;
		$zoneuser  = array();
		$zoneuser  = Class_M_OTHER::get_ajaeks_array(NULL, 3);
		$areauser = array();
		$areauser =  Class_M_OTHER::get_ajaeks_array(NULL, 2);
	}

	if  ($login['staff_auth'] == 'G-4') {
		$area_zone_flg = 4;
	}
	//-----------権限 完了---------------------------------	
	$wherearr =  array();
	if ( isset( $forms['block_cd'] ) &&  ( !empty( $forms['block_cd'] ) ) ){
		$wherearr[] = sprintf(" c.block_cd =  '%s' ",  $forms['block_cd'] );
	}
	
	if  ($forms["sort"] == '2') {
		$wherearr[] = sprintf(" c.area_aja =  '%s' ",  $forms['area_cd'] );
		
	} elseif  ($forms["sort"] == '3') {
		$wherearr[] = sprintf(" c.zone_aja =  '%s' ",  $forms['zone_cd'] );
	}
	
	if ( isset( $forms['shop_cd'] ) &&  ( !empty( $forms['shop_cd'] ) ) ){
		$wherearr[] = sprintf(" c.shop_cd =  '%s' ",  $forms['shop_cd'] );
	}
	/*
	if   ($login['staff_auth'] == 'G-4') {
		$wherearr[] = sprintf(" b.ins_co_cd =  '%s' ",  $_SESSION['ADMIN_LOGIN']['STAFF_INS_CO_CD'] );
	}
	*/
//---CSVダウンロード　処理開始
if ( isset( $_GET['csv'] ) &&  (  $_GET['csv'] == "download" ) ){
	
	$_GET["csv"] = "";
	$tmpfilename = "pattern_detail".date("Ymd_His");
	header("Content-Type: application/octet-stream"); 
	header("Content-Disposition: attachment; filename=$tmpfilename.csv");
	$patterns = $dao->getpatterns();
	//$data     = $dao->getDelives( $patterns, $area_zone_flg);
	
	$data     = $dao->getsearchCsv( $wherearr, $area_zone_flg);
	$colums   = array();
	//列名
	//a.shop_cd, c.shop_name, g.user_name, max(d.u_time) as u_time
	//$colums["name"]  = array('shop_cd','shop_name','media_name','delive_name');
	//$colums["head"]  = array('店コード','店名','媒体','納品先' );
	if ($area_zone_flg == 4) {
		$col_heads = array(
			'matrix_cd'        => array( 'マトリックスID',  1),
			'year4'            => array( '年度',            1),
			'week_cd'          => array( '週',              1),
			'flier_date'       => array( '折込日',          1),
			'local_name'       => array( '都道府県',        1),
			'media_name'       => array( '媒体',            1),
			'delive_name'      => array( '納品先',          1),
			'ins_shop_cd'      => array( 'GEOコード',       1),
			'ins_shop_name'    => array( '販売店名',        1),
			'pper'             => array( '部数％',          1),
			'pnums'            => array( '調整部数',        1),
			'shop_cd'          => array( '店舗コード',  1),
			'shop_name'        => array( '店名',  1),
			'zone_cd'          => array( 'ゾーンAJAコード',  1),
			'zone_nm'          => array( 'ゾーンAJA名',  1),
			'area_cd'          => array( 'エリアAJAコード',  1),
			'area_nm'          => array( 'エリアAJA名',  1)
		);
	} else {
		$col_heads = array(
			'matrix_cd'        => array( 'マトリックスID',  1),
			'year4'            => array( '年度',            1),
			'week_cd'          => array( '週',              1),
			'flier_date'       => array( '折込日',          1),
			'local_name'       => array( '都道府県',        1),
			'media_name'       => array( '媒体',            1),
			'delive_name'      => array( '納品先',          1),
			'ins_shop_cd'      => array( 'GEOコード',       1),
			'ins_shop_name'    => array( '販売店名',        1),
			'pper'             => array( '部数％',          1),
			'pnums'            => array( '調整部数',        1),
			'shop_away'        => array( '店舗からの距離',  1),
			'aoki_compete'     => array( 'AOKI競合',        1),
			'home_percent'     => array( '世帯普及率',      1),
			'all_amount'       => array( '総需要額（億円）',1),
			'sale_share'       => array( '売上高シェア',    1),
			'now_quantity'     => array( '経準高 本年',       1),
			'last_quantity'    => array( '経準高 前年',       1),
			'rate_quantity'    => array( '経準高 前比',       1),
			'diff_quantity'    => array( '経準高 差異',       1),
			'now_sales'        => array( '売上客数 本年',     1),
			'last_sales'       => array( '売上客数 前年',     1),
			'rate_sales'       => array( '売上客数 前比',  1),
			'diff_sales'       => array( '売上客数 差異',  1),
			'now_price'        => array( '客単価 本年',  1),
			'last_price'       => array( '客単価 前年',  1),
			'rate_price'       => array( '客単価 前比',  1),
			'diff_price'       => array( '客単価 差異',  1),
			'shop_cd'          => array( '店舗コード',  1),
			'shop_name'        => array( '店名',  1),
			'zone_cd'          => array( 'ゾーンAJAコード',  1),
			'zone_nm'          => array( 'ゾーンAJA名',  1),
			'area_cd'          => array( 'エリアAJAコード',  1),
			'area_nm'          => array( 'エリアAJA名',  1)
		);
	}

	//列名
	foreach ($col_heads as $k=>$v) {
		$colums["name"][]   = $k;
		$colums["head"][]   = $v[0];
		$colums["type"][$k] = $v[1];
	}

	$colums["pname"] = array();
	foreach ($patterns as $k => $v) {
		$colums["head"][] = $v["pattern_name"];
		$colums["name"][] = $v["col"];
		$colums["type"][$v["col"]] = 1;
	}
	
	$col_heads_last = array(
		'u_time'        => array( '更新日時',       3),
		'c_time'        => array( '登録日時',       3),
		'm_user_name'   => array( '更新者',         1)
	);
	foreach ($col_heads_last as $k=>$v) {
		$colums["name"][]   = $k;
		$colums["head"][]   = $v[0];
		$colums["type"][$k] = $v[1];
	}
	//$local= Class_M_OTHER::get_local_array(  );
	//$block = Class_M_OTHER::get_block_array( );
	
	$week = Class_M_OTHER::get_by_matrix_cd( $matrix_cd );
	$week["flier_date"] =  Class_PWD::int8_to_dateD($week["flier_date"]);
	
	foreach ($data as $k=>$v){ 
		$data[$k]["aoki_compete"] = $aoki_compete_sort[$v["aoki_compete"]];
		//$data[$k]["local_name"] = $local[$v["local_cd"]];
		
		$data[$k]["matrix_cd"]   =  $matrix_cd;
		$data[$k]["year4"]       =  $week["year4"];
		$data[$k]["week_cd"]     =  $week["week_cd"];
		$data[$k]["flier_date"]  =  $week["flier_date"];

	}
	
	$pdatanums = $dao->getPattenNums($wherearr, $area_zone_flg);

	//$patterns = $dao->getpatterns();
	foreach ($data as $k=>$v) {
		foreach ($patterns as $kk=>$vv) {
			if (isset($pdatanums[$v["ins_shop_shop_cd"]][$vv["pattern_cd"]])) {
				$data[$k][$vv["col"]] = $pdatanums[$v["ins_shop_shop_cd"]][$vv["pattern_cd"]];
			}else {
				$data[$k][$vv["col"]] =  "";
			}
		}
	}
	
	$dao->output_csv($data, $colums);
	
	exit;
	
}

/*
function  output_csv($data, $colums )
{
	$old_shop_cd      = "";
	$old_delive_name  = "";
	$old_media_name   = "";
		
	if ( $colums["head"] ) {
		echo   mb_convert_encoding(implode(',',  $colums["head"]), "SJIS-win", "UTF-8")."\n";
	} else {
		echo  implode(',', $colums["name"])."\n";
	}
	
	$sumlinearr  = NULL;
	foreach ($data as $k => $v) {
		
		if ( ($old_shop_cd  != $v["shop_cd"]) || ($old_media_name  != $v["media_name"]) ){
			if ($sumlinearr) {
				foreach ($sumlinearr as $kk=>$vv) {
					$sumlinearr[$kk] = empty($vv)?"":$vv;
				}
				echo  mb_convert_encoding(implode(',', $sumlinearr), "SJIS-win", "UTF-8")."\n";
			} 
			$old_shop_cd      = $v["shop_cd"] ;
			$old_media_name  = $v["media_name"] ;
			
			$sumlinearr  = array("","","","計");
		}
		
		$linearr  = array();
		foreach ($colums["name"]  as $ck => $cv) {
			$linearr[]= $v[$cv];
		}
		
		foreach ($colums["pname"]  as $ck => $cv) {
			$linearr[]=  isset($v[$cv]) ?  $v[$cv] : "";
			$val    = isset($v[$cv]) ? nulltonum($v[$cv]) : 0;
			$valsum = isset($sumlinearr[$cv]) ? nulltonum($sumlinearr[$cv]) : 0;
			
			$sumlinearr[$cv] = $val + $valsum;
		}
		
		echo  mb_convert_encoding(implode(',', $linearr), "SJIS-win", "UTF-8")."\n";
	}	
}
*/
function  nulltonum($value ){
	if (is_numeric($value)) {
		return (int)$value;
	}
	return 0;
}

//---CSVダウンロード　処理完了
$isG6_7 = FALSE;
if   ($login['staff_auth'] == 'G-2' || $login['staff_auth'] == 'G-3' || $login['staff_auth'] == 'G-4')  {
	$isG6_7 = TRUE;
}
$block = Class_M_OTHER::get_block_array( PLEASE_SELECT_ARR );
$smarty->assign('block', $block );
//================AJAゾーンエリア==================


if( isset($zoneuser) )    $smarty->assign('zoneuser', $zoneuser);
if( isset($areauser) )    $smarty->assign('areauser', $areauser);
//================AJAゾーンエリア==================
if ( empty( $forms["sort"] ) ) {
	$forms["sort"] = "";
}
$aoki_area_zones = array();

if (($login_auth == 'G-2' ) || ($login_auth == 'G-3' ))  {
	foreach ($aoki_area_zone as $k => $v) {
		if ($k == $forms["sort"] ) {
			$aoki_area_zones[$k] = $v;
		} 
	}
}else {
	$aoki_area_zones[""] = "すべて";
	foreach ($aoki_area_zone as $k => $v) {
		$aoki_area_zones[$k] = $v;
	}
}
$smarty->assign('sorts', $aoki_area_zones );
//==================================周
if (empty($forms["year4"])) {
	$forms["year4"] = date('Y');
}
$smarty->assign('year4',  Class_PWD::get_years());

$week = Class_M_OTHER::get_week_array( $forms["year4"], PLEASE_SELECT_ARR, TRUE );

$smarty->assign('week', $week );
$smarty->assign('forms',  $forms);
//==================================周

$smarty->assign('isG6_7', $isG6_7 );

$smarty->assign('menu', $smarty->fetch('menu.html') );
$smarty->assign('logout', $smarty->fetch('logout.html') );
$smarty->assign('footer', $smarty->fetch('footer.html') );
//$smarty->assign('pageing', $smarty->fetch('page.html') );
$smarty->display('tpattern_export.html');

?>